package com.ywj.websocket.client;

import lombok.extern.slf4j.Slf4j;

import javax.websocket.*;
import java.net.MalformedURLException;
import java.net.URI;


/**
 * socket推送消息（客户端）
 */
@ClientEndpoint
@Slf4j
public class SocketClient1 {

    private Session session;

//    public SocketClient(Session session){
//        this.session = session;
//    }

    @OnOpen
    public void onOpen(Session session) {
        log.info("SocketClient:------打开socket--------");
        System.out.println("WebSocket opened: " + session.getId());
        this.session = session;
    }

    @OnMessage
    public void onMessage(String message) {
        log.info("SocketClient:-----接受服务端消息-----"+message);
        System.out.println("Received message: " + message);
    }

    @OnClose
    public void onClose(Session session, CloseReason closeReason) {
        log.info("SocketClient:----关闭socket链接");
        System.out.println("WebSocket closed with reason: " + closeReason.getReasonPhrase());
    }

    public void connect(String uri) {
        try {
            WebSocketContainer container = ContainerProvider.getWebSocketContainer();
//            container.connectToServer(this, new URI(uri));
            container.connectToServer(this, new URI(uri));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void sendMessage(String message) {
        try {
            session.getBasicRemote().sendText(message);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws MalformedURLException {
        SocketClient1 client = new SocketClient1();
        System.out.println("客户端已启动");
        String url = "ws://127.0.0.1:8080/ws/123456";
//        client.connect(url);
        client.connect("ws://127.0.0.1:8080/ws/123456");
        client.sendMessage("I want a server!");
//        SocketClient client = new SocketClient(new URL(url));
//        client.connect();
//        Thread.sleep(5000);
//        client.send("hello who you are");
//        client.close();

    }

}


